package cn.lzh.cqhg1.controller;

import cn.lzh.cqhg1.Bean.DLlog;
import cn.lzh.cqhg1.Bean.User;
import cn.lzh.cqhg1.dao.DLlogDao;
import cn.lzh.cqhg1.dao.UserDao;
import cn.lzh.cqhg1.utils.AjaxResult;
import cn.lzh.cqhg1.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController extends BaseController{
    @Autowired
    UserDao userDao;
    @Autowired
    DLlogDao dLlogDao;



    @PostMapping("/userlogin")
    @ResponseBody
    public AjaxResult login(String username,String password){

        User user = userDao.findByUsernameAndPassword(username,Utils.getMD5String(password));

        if(Utils.isNull(user)){
            return AjaxResult.error();
        }else{

            getSession().setAttribute("username",user.getUsername());
            getSession().setAttribute("user",user);
            getSession().setMaxInactiveInterval(86400);



            DLlog dllog = new DLlog();
            dllog.setUsername(user.getUsername());
            dllog.setStatus(1);
            dLlogDao.save(dllog);

            Map<String,Object> map = new HashMap<>();
            map.put("status",user.getStatus());
            map.put("type",user.getType());

            return AjaxResult.success(map);
        }

    }
    @GetMapping("/logout")
    @ResponseBody
    public AjaxResult logout() {
        try {
            getSession().invalidate();
        } catch (Exception ignored) {

        }
        return AjaxResult.success();
    }
    //转到主页
    @GetMapping("/main")
    public String main(){
        return "public/main";
    }

}
